<template>
  <view class="w100 bg-gray flex-sub flex flex-col">
    <u-navbar
      :safeAreaInsetTop="true"
      :title="isAdmin ? '公司报表' : '下级列表'"
      :fixed="true"
      :autoBack="!isAdmin"
      left-text="返回"
    >
      <view v-if="isAdmin" slot="left">
        <slot></slot>
      </view>
    </u-navbar>
    <view
      :style="{ 'margin-top': '30px' }"
      class="w100 flex-sub padding-lr padding-top flex-center flex-direction"
    >
      <view class="bg-white w100 padding-lr text-sm">
        <u-picker
          :show="showPicker"
          :columns="columns"
          :value="dataPicker"
          closeOnClickOverlay
          @confirm="dataPickerConfirm"
          @cancel="dataPickerClose"
          @close="dataPickerClose"
        ></u-picker>
        <u-cell :border="false">
          <view
            class="flex_con"
            slot="title"
            >
            <view class="text-df text-bold flex_text" @click="showPicker = true">
              {{ dataPicker }}
            </view>
            <u-button
              v-if="isAdmin" 
              style="flex: 0; margin-left: 10px"
              type="primary"
              size="mini"
              class="status_btn"
              :color="$u.color.error"
              @click="changeCurPorStatus"
            >
              <view class="text-sm" style="white-space: pre">{{
                curProStatus  === "pdd" ? "拼多多" :curProStatus  === "jd" ?"京东": "淘宝"
              }}</view>
            </u-button>
          </view>
          <view v-if="!isAdmin" class="text-grey text-sm" slot="value"
            >总计{{ total }}</view
          >
        </u-cell>
      </view>
      <z-paging
        class="flex-sub padding-lr bg-white"
        ref="paging"
        :default-page-size="limit"
        v-model="sonList"
        :refresher-enabled="true"
        :auto-clean-list-when-reload="false"
        :auto-scroll-to-top-when-reload="true"
        :show-default-loading-more-text="true"
        loading-more-no-more-text="没有更多了"
        :fixed="false"
        :pagingStyle="{
          height: `calc( 100vh - ${statusBarHeight + tabHeight}px )`,
        }"
        @query="queryList"
      >
        <view
          class="rcl-notice__item"
          v-for="(item, index) in sonList"
          :key="index"
          @click="accountClick(index)"
        >
          <u-cell-group>
            <u-cell :border="false">
              <view class="flex text-cut" slot="title"
                >
                <u-tag :text="item.id" size="mini" type="primary" />
                <view
                  style="width: 100px"
                  class="flex-sub text-cut margin-left-xs text-bold"
                >
                  {{ isAdmin ? item.account : item.name }}
                </view>
              </view>
              <view
                class="text-sm flex margin-top justify-between"
                slot="label"
                v-if="isAdmin"
              >
                <view class="flex-col">
                  <view>总消耗</view>
                  <view class="item_value">{{ item.cost }}</view>
                </view>
                <view class="flex-col align-center">
                  <view>总销售</view>
                  <view class="item_value">{{ item.sales }}</view>
                </view>
                <view class="flex-col align-end">
                  <view>有效销售</view>
                  <view class="item_value">{{ item.effective_sales }}</view>
                </view>
              </view>
              <view
                class="text-sm flex margin-top justify-between"
                slot="label"
                v-if="isAdmin"
              >
                <view class="flex-col">
                  <view>订单数</view>
                  <view class="item_value">{{ item.order_num }}</view>
                </view>
                <view class="flex-col align-center">
                  <view>ROI</view>
                  <view class="item_value">{{ item.ROI }}</view>
                </view>
                <view class="flex-col align-end">
                  <view>有效ROI</view>
                  <view class="item_value">{{ item.effective_ROI }}</view>
                </view>
              </view>
              <view
                class="text-sm flex margin-top justify-between"
                slot="label"
                v-if="!isAdmin"
              >
                <view class="flex-col">
                  <view>销售</view>
                  <view class="item_value">{{ item.sales }}</view>
                </view>
                <view class="flex-col align-center">
                  <view>消耗</view>
                  <view class="item_value">{{ item.cost }}</view>
                </view>
                <view class="flex-col align-end">
                  <view>ROI</view>
                  <view class="item_value">{{ item.ROI }}</view>
                </view>
              </view>
            </u-cell>
            <u-cell
              style="margin-top: -10px"
              :border="false"
              :value="isAdmin ? '' : '查看详情'"
              :right-icon="isAdmin ? '' : 'arrow-right'"
              :isLink="true"
              :disabled="true"
              arrow-direction="right"
              v-if="!isAdmin"
            >
              <view style="width: 200px" class="text-sm text-cut" slot="title">
                展示次数: {{ item.show }}
              </view>
            </u-cell>
          </u-cell-group>
        </view>
      </z-paging>
    </view>
  </view>
</template>

<script>
import dayjs from "dayjs";
import { sonList,getAccountLogin } from "@/api";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      sonId: undefined,
      total: 0,
      page: 1,
      limit: 10,
      statusBarHeight: 10,
      tabHeight: 0,
      showPicker: false,
      sonList: [],
      columns: [["今日", "昨日", "本周", "上周", "本月", "上月"]],
      dataPicker: "今日",
    };
  },
  onLoad(option) {
    console.log("option===", option);
    this.sonId = option.sonId || undefined;
    this.queryDate = option.queryDate;
    this.dataPicker = this.queryDate || "今日";
  },
  computed: {
    ...mapGetters(["isAdmin", "curProStatus"]),
    dateParams() {
      let start_date;
      let end_date = dayjs().format("YYYY-MM-DD");
      switch (this.dataPicker) {
        case "今日":
          start_date = dayjs().format("YYYY-MM-DD");
          break;
        case "昨日":
          start_date = end_date = dayjs()
            .subtract(1, "day")
            .format("YYYY-MM-DD");
          break;
        case "本周":
          start_date = dayjs()
            .subtract((dayjs().day() || 7) - 1, "day")
            .format("YYYY-MM-DD");
          break;
        case "本月":
          start_date = dayjs().format("YYYY-MM-01");
          break;
        case "上周":
          start_date = dayjs().subtract(7, "day").format("YYYY-MM-DD");
          break;
        case "上月":
          start_date = dayjs().subtract(1, "month").format("YYYY-MM-DD");
          break;
        default:
          start_date = dayjs().format("YYYY-MM-DD");
          break;
      }
      return {
        start_date,
        end_date,
      };
    },
  },
  methods: {
    changeCurPorStatus() {
      this.$store.commit(
        "SET_CUR_PRO_STATUS",
        this.curProStatus == "pdd" ? "tb":this.curProStatus == "tb"?"jd":"pdd"
      );
      window.location.reload();
    },
    accountClick(idx) {
      if (this.isAdmin){
       console.log( this.sonList[idx])
       getAccountLogin({
        login_merchant_id:this.sonList[idx].merchant_id,
      }).then(({ data }) => {
        console.log(data)
        const baseUrl = 'https://www.tianjing.site/#/page/dashboard.html';
        const params = new URLSearchParams([
          ['token', data.token],
          ['account', this.sonList[idx].account],
          ['checkPass', '1'],
          ['role', data.role],
          ['is_vip', this.sonList[idx].is_vip === 1 ? 'true' : 'false']
        ]);
        const url = `${baseUrl}?${params.toString()}`;
        window.open(url, '_blank');
      });
       return;
      };
      const sonId = this.sonList[idx]?.id;
      return uni.navigateTo({
        url: `/pages/index/sub/subIndex?sonId=${sonId}&queryDate=${this.queryDate}`,
      });
    },
    setCookie(domain, name, value, days) {
       var expires = '';
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toUTCString();
  }
  document.cookie = name + '=' + (value || '') + expires + '; path=/; domain=' + domain;
},
    queryList(pageNo, pageSize) {
      this.page = pageNo;
      this.handleGetList();
    },

    handleGetList() {
      console.log(this.curProStatus)
      sonList({
        channel: this.curProStatus == "pdd" ? 1 :this.curProStatus == "jd" ? 4: 3,
        son_id: +this.sonId,
        page: this.page,
        page_size: this.isAdmin ? 50 : this.limit,
        ...this.dateParams,
      }).then(({ data }) => {
        this.$refs.paging.complete(data.list);
        this.total = data.total;
      });
    },
    hideKeyboard() {
      uni.hideKeyboard();
    },
    dataPickerConfirm(e) {
      this.showPicker = false;

      this.dataPicker = e?.value?.[0];
      this.$nextTick(() => {
        this.queryList(1);
      });
    },
    dataPickerClose() {
      this.showPicker = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.content {
  height: 100%;
}
.item_value {
  color: #0b84b8
}
.flex_con {
  display: flex;
  justify-content: space-between;
}
.status_btn {
  width: 60px;
}
.flex_text {
  flex: 1
}
</style>
